package cn.line5.organization;

import java.util.List;
import java.util.Map;

import cn.line5.module.ModuleConstants;
import cn.line5.module.ModuleDao;
import cn.line5.module.ModuleFunctionPointVo;
import cn.line5.module.ModuleFunctionVo;
import cn.line5.module.ModuleVo;
import cn.line5.seam.annotations.In;
import cn.line5.seam.annotations.Name;
import cn.line5.seam.annotations.Transaction;
import cn.line5.seam.db.IDGenerator;
import cn.line5.seam.db.PageResult;

@Name("organizationService")
/**
 * <h1>机构用户业务层实现类</h1>
 * 
 * @author Liu,Xiaojun
 */
public class OrganizationServiceImpl implements OrganizationService {
	@In("organizationDao")
	private OrganizationDao organizationDao;
	@In("moduleDao")
	private ModuleDao moduleDao;

	/**
	 * 获取机构的所有列表-递归方法
	 */
	public List<OrganizationVo> getOrganizationList(String parentId) {
		List<OrganizationVo> list = organizationDao
				.getOrganizationList(parentId != null
						&& !OrganizationConstants.ROOT_ORGANIZATION_ID
								.equals(parentId) ? parentId : "");
		if (list != null && list.size() > 0)
			for (OrganizationVo vo : list)
				vo.setList(getOrganizationList(vo.getOrganizationId()));
		return list;
	}

	/**
	 * 获取树的JS代码
	 */
	public String getOrganizationTreeJs() {
		OrganizationVo vo = getRootOrganization();
		return new StringBuffer().append(
				"var tree = new MzTreeView(\"tree\");\n").append(
				"tree.setIconPath(\"../images/MzTree/\");\n").append(
				"tree.nodes[\"-1_").append(vo.getOrganizationId()).append(
				"\"] = \"text:").append(vo.getOrganizationName()).append(
				"\";\n").append(getOrganizationTreeJs(vo.getOrganizationId()))
				.append("tree.setURL(\"organizationMain.seam\");\n").append(
						"tree.setTarget(\"organizationMain\");\n").append(
						"document.write(tree.toString());\n").toString();
	}

	/**
	 * 获取设置权限的模块功能的所有列表html-递归方法
	 */
	public String getModuleHtml(String parentId, Map<String, PermissionVo> map) {
		StringBuffer html = new StringBuffer();
		List<ModuleVo> list = moduleDao.getModuleList(parentId != null
				&& !ModuleConstants.ROOT_MODULE_ID.equals(parentId) ? parentId
				: "");
		if (list != null && list.size() > 0)
			for (ModuleVo vo : list) {
				html.append("<tr><th class=\"spec\" style=\"padding-left: ")
						.append(parentId.length() / 3 * 20).append("px;\">");
				html
						.append(
								"<input type=\"checkbox\" name=\"permissionModuleIds\" onclick=\"checkIt(this)\" ")
						.append(
								map.containsKey(vo.getModuleId()) ? "checked"
										: "").append(" value=\"").append(
								vo.getModuleId()).append("\"/>").append(
								vo.getModuleName()).append("</th></tr>");
				if (ModuleConstants.MODULE_TYPE_NODE.equals(vo.getModuleType()))
					html.append(getModuleHtml(vo.getModuleId(), map));
				else if (ModuleConstants.MODULE_TYPE_FUNCTION.equals(vo
						.getModuleType()))
					html.append(getFunctionHtml(vo.getModuleId(), map));
			}
		return html.toString();
	}

	/**
	 * 获取机构下拉菜单的html代码-递归方法
	 */
	public String getOrganizationSelectHtml(String parentId, String t) {
		List<OrganizationVo> list = organizationDao
				.getOrganizationList(parentId);
		StringBuffer html = new StringBuffer();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				OrganizationVo vo = list.get(i);
				html.append("<option value=\"").append(vo.getOrganizationId())
						.append("\">").append(t);
				if (parentId.length() > 0) {
					html.append("└");
				}
				html.append(vo.getOrganizationName()).append("</option>")
						.append(
								getOrganizationSelectHtml(vo
										.getOrganizationId(), t
										+ ((i < (list.size() - 1)) ? "︱"
												: "&nbsp;&nbsp;&nbsp;")));
			}
		}
		return html.toString();
	}

	/**
	 * 机构列表
	 */
	public PageResult<OrganizationVo> getOrganizationPageList(String parentId,
			String currentPage) {
		PageResult<OrganizationVo> result = organizationDao
				.getOrganizationPageList(
						parentId != null
								&& !OrganizationConstants.ROOT_ORGANIZATION_ID
										.equals(parentId) ? parentId : "",
						(currentPage != null && currentPage.length() > 0 ? Integer
								.parseInt(currentPage)
								: 1));
		covertOrganizationList(result.getResultList());
		return result;
	}

	/**
	 * 获取机构信息
	 */
	public OrganizationVo getOrganization(String organizationId) {
		if (organizationId != null
				&& organizationId.length() > 0
				&& !OrganizationConstants.ROOT_ORGANIZATION_ID
						.equals(organizationId))
			return covert(organizationDao.getOrganization(organizationId));
		else
			return covert(getRootOrganization());
	}

	/**
	 * 添加机构
	 */
	public Boolean addOrganization(OrganizationVo vo) {
		String organizationId = vo.getParentId() != null
				&& !OrganizationConstants.ROOT_ORGANIZATION_ID.equals(vo
						.getParentId()) ? vo.getParentId() : "";
		vo.setOrganizationSort(organizationDao
				.getOrganizationMaxSort(organizationId) + 1);
		String maxId = organizationDao.getOrganizationMaxId(organizationId);
		int _maxId = Integer.parseInt(maxId.substring(maxId.length() - 3)) + 1;
		if (_maxId > 999)
			return false;
		else if (_maxId > 99)
			organizationId += _maxId;
		else if (_maxId > 9)
			organizationId += "0" + _maxId;
		else
			organizationId += "00" + _maxId;
		vo.setOrganizationId(organizationId);
		return organizationDao.addOrganization(vo);
	}

	/**
	 * 修改机构
	 */
	public Boolean modifyOrganization(OrganizationVo vo) {
		return organizationDao.modifyOrganization(vo);
	}

	/**
	 * 机构向上排序
	 */
	@Transaction
	public Boolean upOrganization(String organizationId) {
		List<OrganizationVo> list = organizationDao
				.getOrganizationList(organizationId.substring(0, organizationId
						.length() - 3));
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				OrganizationVo vo1 = list.get(i);
				if (vo1.getOrganizationId().equals(organizationId)) {
					if (i > 0) {
						OrganizationVo vo2 = list.get(i - 1);
						Integer organizationSort = vo1.getOrganizationSort();
						vo1.setOrganizationSort(vo2.getOrganizationSort());
						vo2.setOrganizationSort(organizationSort);
						return organizationDao.saveOrganizationSort(vo1)
								&& organizationDao.saveOrganizationSort(vo2);
					}
					break;
				}
			}
		}
		return false;
	}

	/**
	 * 机构向下排序
	 */
	@Transaction
	public Boolean downOrganization(String organizationId) {
		List<OrganizationVo> list = organizationDao
				.getOrganizationList(organizationId.substring(0, organizationId
						.length() - 3));
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				OrganizationVo vo1 = list.get(i);
				if (vo1.getOrganizationId().equals(organizationId)) {
					if (i < list.size() - 1) {
						OrganizationVo vo2 = list.get(i + 1);
						Integer organizationSort = vo1.getOrganizationSort();
						vo1.setOrganizationSort(vo2.getOrganizationSort());
						vo2.setOrganizationSort(organizationSort);
						return organizationDao.saveOrganizationSort(vo1)
								&& organizationDao.saveOrganizationSort(vo2);
					}
					break;
				}
			}
		}
		return false;
	}

	/**
	 * 删除机构
	 */
	@Transaction
	public Boolean deleteOrganization(String[] organizationIds) {
		Boolean t = true;
		for (String organizationId : organizationIds)
			t &= organizationDao.deleteOrganization(organizationId);
		return t;
	}

	/**
	 * 用户列表
	 */
	public PageResult<UserVo> getUserPageList(String organizationId,
			String currentPage) {
		PageResult<UserVo> result = organizationDao.getUserPageList(
				organizationId != null ? organizationId : "",
				(currentPage != null && currentPage.length() > 0 ? Integer
						.parseInt(currentPage) : 1));
		covertUserList(result.getResultList());
		return result;
	}

	/**
	 * 获取用户信息
	 */
	public UserVo getUser(String userId) {
		return covert(organizationDao.getUser(userId));
	}

	/**
	 * 检测用户名是否被占用
	 */
	public Boolean checkLoginName(String loginName) {
		return organizationDao.getUserByLoginName(loginName.toLowerCase()) == null;
	}

	/**
	 * 检测机构下是否有用户
	 */
	public Boolean checkHaveUser(String[] organizationIds) {
		for (String organizationId : organizationIds) {
			if (organizationDao.getUserCountByOrganizationId(organizationId) > 0)
				return true;
		}
		return false;
	}

	/**
	 * 添加用户
	 */
	public Boolean addUser(UserVo vo) {
		vo.setUserId(IDGenerator.UUID());
		vo.setLoginNum(0);
		vo.setStatus(OrganizationConstants.USER_TYPE_NORMAL);
		vo.setLoginName(vo.getLoginName().toLowerCase());
		return organizationDao.addUser(vo);
	}

	/**
	 * 修改用户
	 */
	public Boolean modifyUser(UserVo vo) {
		return organizationDao.modifyUser(vo);
	}

	/**
	 * 锁定用户
	 */
	@Transaction
	public Boolean lockUser(String[] userIds) {
		Boolean t = true;
		for (String userId : userIds) {
			UserVo vo = new UserVo();
			vo.setUserId(userId);
			vo.setStatus(OrganizationConstants.USER_TYPE_LOCKED);
			t &= organizationDao.modifyUserStatus(vo);
		}
		return t;
	}

	/**
	 * 解除锁定用户
	 */
	@Transaction
	public Boolean unlockUser(String[] userIds) {
		Boolean t = true;
		for (String userId : userIds) {
			UserVo vo = new UserVo();
			vo.setUserId(userId);
			vo.setStatus(OrganizationConstants.USER_TYPE_NORMAL);
			t &= organizationDao.modifyUserStatus(vo);
		}
		return t;
	}

	/**
	 * 初始化用户密码
	 */
	@Transaction
	public Boolean resetUserPassword(String[] userIds) {
		Boolean t = true;
		for (String userId : userIds) {
			UserVo vo = new UserVo();
			vo.setUserId(userId);
			vo.setLoginPassword(OrganizationConstants.INIT_PASSWORD);
			t &= organizationDao.modifyLoginPassword(vo);
		}
		return t;
	}

	/**
	 * 删除用户
	 */
	@Transaction
	public Boolean deleteUser(String[] userIds) {
		Boolean t = true;
		for (String userId : userIds)
			t &= organizationDao.deleteUser(userId);
		return t;
	}

	/**
	 * 调整机构
	 */
	@Transaction
	public Boolean changeOrganization(String[] userIds, String newOrganizationId) {
		Boolean t = true;
		for (String userId : userIds) {
			UserVo vo = new UserVo();
			vo.setUserId(userId);
			vo.setOrganizationId(newOrganizationId);
			t &= organizationDao.modifyOrganization(vo);
		}
		return t;
	}

	/**
	 * 设置用户权限
	 */
	@Transaction
	public Boolean setPermission(String userId, String[] permissionModuleIds,
			String[] permissionFunctionIds) {
		Boolean t = organizationDao.removePermission(userId);
		if (permissionModuleIds != null && permissionModuleIds.length > 0)
			for (String moduleId : permissionModuleIds) {
				PermissionVo vo = new PermissionVo();
				vo.setUserId(userId);
				vo.setPermissionId(moduleId);
				vo
						.setPermissionType(OrganizationConstants.PERMISSION_TYPE_MODULE);
				t &= organizationDao.addPermission(vo);
			}
		if (permissionFunctionIds != null && permissionFunctionIds.length > 0)
			for (String functionId : permissionFunctionIds) {
				PermissionVo vo = new PermissionVo();
				vo.setUserId(userId);
				vo.setPermissionId(functionId);
				vo
						.setPermissionType(OrganizationConstants.PERMISSION_TYPE_FUNCTION);
				t &= organizationDao.addPermission(vo);
				List<ModuleFunctionPointVo> list = moduleDao
						.getPointList(functionId);
				if (list != null && list.size() > 0)
					for (ModuleFunctionPointVo pointVo : list) {
						PermissionVo _vo = new PermissionVo();
						_vo.setUserId(userId);
						_vo.setPermissionId(String
								.valueOf(pointVo.getPointId()));
						_vo
								.setPermissionType(OrganizationConstants.PERMISSION_TYPE_POINT);
						t &= organizationDao.addPermission(_vo);
					}
			}
		return t;
	}

	/**
	 * 获取根机构信息
	 */
	private OrganizationVo getRootOrganization() {
		OrganizationVo vo = new OrganizationVo();
		vo.setOrganizationId(OrganizationConstants.ROOT_ORGANIZATION_ID);
		vo.setOrganizationName(OrganizationConstants.ROOT_ORGANIZATION_NAME);
		vo.setOrganizationSort(0);
		return vo;
	}

	/**
	 * 组装机构列表信息
	 */
	private List<OrganizationVo> covertOrganizationList(
			List<OrganizationVo> list) {
		for (OrganizationVo vo : list)
			covert(vo);
		return list;
	}

	/**
	 * 组装机构信息
	 */
	private OrganizationVo covert(OrganizationVo vo) {
		if (vo == null)
			return null;
		vo.setIsEdit(vo.getOrganizationId() != null
				&& vo.getOrganizationId().length() > 0
				&& !OrganizationConstants.ROOT_ORGANIZATION_ID.equals(vo
						.getOrganizationId()));
		return vo;
	}

	/**
	 * 组装用户列表信息
	 */
	private List<UserVo> covertUserList(List<UserVo> list) {
		for (UserVo vo : list)
			covert(vo);
		return list;
	}

	/**
	 * 组装用户信息
	 */
	private UserVo covert(UserVo vo) {
		if (vo == null)
			return null;
		vo.setStatusName(OrganizationConstants.USER_TYPE_NORMAL.equals(vo
				.getStatus()) ? OrganizationConstants.USER_TYPE_NORMAL_NAME
				: OrganizationConstants.USER_TYPE_LOCKED_NAME);
		vo.setGenderName(OrganizationConstants.GENDER_MAN
				.equals(vo.getGender()) ? OrganizationConstants.GENDER_MAN_NAME
				: OrganizationConstants.GENDER_WOMAN_NAME);
		return vo;
	}

	/**
	 * 获取机构树JS代码-递归方法
	 */
	private String getOrganizationTreeJs(String parentId) {
		StringBuffer sb = new StringBuffer();
		List<OrganizationVo> list = organizationDao
				.getOrganizationList(!OrganizationConstants.ROOT_ORGANIZATION_ID
						.equals(parentId) ? parentId : "");
		if (list != null && list.size() > 0) {
			for (OrganizationVo vo : list) {
				sb.append("tree.nodes[\"").append(parentId).append("_").append(
						vo.getOrganizationId()).append("\"] = \"text:").append(
						vo.getOrganizationName()).append(
						"; data:organizationId=")
						.append(vo.getOrganizationId()).append("\";\n").append(
								getOrganizationTreeJs(vo.getOrganizationId()));
			}
		}
		return sb.toString();
	}

	/**
	 * 获取模块下功能权限的html代码
	 */
	private String getFunctionHtml(String moduleId,
			Map<String, PermissionVo> map) {
		StringBuffer html = new StringBuffer();
		List<ModuleFunctionVo> list = moduleDao.getFunctionList(moduleId);
		if (list != null && list.size() > 0) {
			html.append("<tr><th class=\"specalt\" style=\"padding-left: ")
					.append(moduleId.length() / 3 * 20).append("px;\">");
			for (ModuleFunctionVo vo : list) {
				html
						.append(
								"<input type=\"checkbox\" name=\"permissionFunctionIds\" onclick=\"checkIt(this)\" ")
						.append(
								map.containsKey(vo.getFunctionId()) ? "checked"
										: "").append(" value=\"").append(
								vo.getFunctionId()).append("\"/>").append(
								vo.getFunctionName()).append("&nbsp;");
			}
			html.append("</th></tr>");
		}
		return html.toString();
	}
}
